Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

253
Views
Mangosta | rellenar en post middleware para "guardar"

Considere los siguientes parentSchema y childSchema :

 const parentSchema = new mongoose.Schema({ name: String, children: [{ type: mongoose.Schema.Types.ObjectId, ref: "Child" }], }); const childSchema = new mongoose.Schema({ name: String, parent: { type: mongoose.Schema.Types.ObjectId, ref: "Parent" }, });

¿Cómo accedo al nombre del padre dentro de un middleware posterior al childSchema? Estoy probando el código a continuación, pero al parent se le asigna el ObjectId en lugar del modelo principal real.

 childSchema.post("save", async function (child) { const parent = child.populate("parent").parent; });

¿Cuál es la forma correcta de hacer esto?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Si desea completar algo después de la búsqueda inicial, debe llamar a execPopulate , por ejemplo:

 childSchema.post("save", async function (child) { try { if (!child.populated('parent')) { await child.populate('parent').execPopulate(); } const parent = child.populate("parent").parent; } catch (err) {} });
over 4 years ago · Santiago Trujillo Report

0

Acabo de enterarme de this.model("Model") , así que estoy compartiendo otra solución. Sin embargo, no estoy seguro de cómo se compara con el aceptado:

 childSchema.post("save", async function (child) { try { const parent = await this.model("Parent").findOne({ _id: child.parent }); parent.children.push(child._id); parent.save(); } catch (error) {} });
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!